/*******************************************************************************
 * 版权：北京润尼尔网络科技有限公司，保留所有版权<br>
 * 版本：v1.0.0<br>
 * 文件：DeviceEditPart.js<br>
 * 日期：2016年9月20日<br>
 * 作者:王志远<br>
 * 功能：器件编辑件<br>
 * 
 * 修改记录：<br>
 * 日期 描述 更新功能<br>
 ******************************************************************************/

window.makeNamespace(window,"Rainier.UI.V2");

/**
 * 类型名称：Rainier.UI.V2.CompositeEditPart<br>
 * 类型功能：器件编辑件<br>
 */
Rainier.UI.V2.DeviceEditPart = Rainier.UI.V2.CompositeEditPart.extend({
	
	NAME : "Rainier.UI.V2.DeviceEditPart",
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.init<br>
	 * 函数功能：构造函数<br>
	 * 异常信息：无<br>
	 */
	init : function(){
		
		this._super();

		this.messageNum = 0;
	},
	
	onFigureDbclick : function(emitter, figure){
		var model = this.getModel();
		if(model){
			if(model instanceof Rainier.UI.V2.VirtualModel){
				model.startCvi();
			}
			// else if(model instanceof Rainier.UI.V2.PmsModel){
			// 	//福州大学特殊处理
			// 	var uiProperty = model.getProperty().uiProperty;
			// 	if (uiProperty.waveimage) {
			// 		var height = uiProperty.waveheight;
			// 		var width = uiProperty.wavewidth;
			// 		var title = model.getProperty().modelProperty.componentName;
			// 		var dialog = new Rainier.UI.V2.WaveDialog({height:height,width:width,image:uiProperty.waveimage,title:title});
			// 		dialog.dialog.open();
			// 	}
			// }
		}
	},
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.onFigureContextMenu<br>
	 * 函数功能：当图元右键菜单时触发<br>
	 * 参数输入：emitter : canvas图元对象<br>
	 * 参数输入：figure  : 触发事件时，传递的参数(包含：figure图元、x值，y值，ctrl值，shfit值)<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	onFigureContextMenu : function(emitter, figure){
		if(figure.figure instanceof draw2d.Figure){
			var canvas = figure.figure.getCanvas();
			var selection = canvas.getSelection().getAll();
			if(!selection.contains(figure.figure)){
				selection.each(function(index,select){					
					var selectionStuff = window.AppContext.getSelectionStuff();
					var ctx            = selectionStuff.activeEditor.context;
					var editPart       = ctx.findEditPartByFigure(select);
					editPart.model.deactive();
				})
				var point = canvas.fromCanvasToDocumentCoordinate(figure.x,figure.y);
				canvas.setCurrentSelection(figure.figure);
				canvas.mouseDownX = point.x;
				canvas.mouseDownY = point.y;
			}
			var canvasEditPart = canvas.context.findEditPartByFigure(canvas);
			var deviceMenu = new Rainier.UI.V2.DeviceMenu(canvasEditPart,figure);
			deviceMenu.show();
		}
	},
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.createFigure<br>
	 * 函数功能：创建连接图元<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	createFigure : function(){
		var model = this.model;
		var prop  = model.property;
		if(!this.figure){
			//创建box图元
			var thisFigure 	= new Rainier.UI.V2.DeviceBoxFigure(prop);
			
			//填充图片
			var imageProperty = {};
			imageProperty.width = prop.imageProperty.width;
			imageProperty.height= prop.imageProperty.height;
			imageProperty.svg   = prop.imageProperty.svg;
			
			//设置器件Label
			thisFigure.setSymbolLabelFigure(
				{
					text 		: prop.modelProperty.label,
					fontSize	: 14,
					bold		: true,
					fontColor	:'#ffffff',
					visible		: false,
				},
				'Rainier.UI.V2.DeviceLabelLocator',
				thisFigure.width/2 + 5,
				-20
			);
			
			//设置参数标签
			thisFigure.setParameterFigure(
				{
					text 		: prop.modelProperty.label,
					fontSize	: 14,
					bold		: true,
					fontColor	:'#ffffff',
					visible		: false,
				},
				'Rainier.UI.V2.DeviceLabelLocator',
				thisFigure.width + 5,
				thisFigure.height/2 - 10		
			);
			
			//设置参数标签
			thisFigure.setDeviceNameFigure(
				{
					text 		: prop.modelProperty.componentName,
					fontSize	: 14,
					bold		: true,
					fontColor	:'#ffffff',
					visible		: false,
				},
				'Rainier.UI.V2.DeviceLabelLocator',
				0,
				thisFigure.height +10		
			);

			this.figure = thisFigure;
			var inputs = model.getInputPorts();
			inputs.each($.proxy(this.addPortFigure,this));
			
			var outputs = model.getOutputPorts();
			outputs.each($.proxy(this.addPortFigure,this));
			
			var hybirds = model.getHybridPorts();
			hybirds.each($.proxy(this.addPortFigure,this));
		}			
		
		this.fillFigure();
		var paraString = this.refreshParameters();
		
		this.figure.unshowPortNumber();
		this.figure.unshowPortSymbol();
		this.figure.unshowLabel();
		this.figure.unshowParameter();
		this.figure.unshowDeviceName();
		
		var context       = this.getParent().context;
		var showDevice    = context.menuItemUsedInfo.deviceInfoUsed;
		var deviceShowAll = context.menuItemUsedInfo.deviceShowAll;
		
		if(paraString && showDevice){
			this.figure.showParameter();
		}
		
		if(prop.modelProperty){
			var showInfo = prop.modelProperty.showInfo;
			if(showInfo && showDevice){
				var showLabel 			= showInfo.showLabel;
				var showPinNumber		= showInfo.showPinNumber;
				var showPinSymbol		= showInfo.showPinSymbol;
				var showComponentName	= showInfo.showComponentName; 
				
				if((showLabel && showLabel.showable && showLabel.visiable)){
					this.figure.showLabel();
				}
				
				if((showPinNumber && showPinNumber.showable && showPinNumber.visiable) || (deviceShowAll && showPinSymbol && showPinSymbol.showable)){
					this.figure.showPortNumber();
				}
				
				if((showPinSymbol && showPinSymbol.showable && showPinSymbol.visiable)  || (deviceShowAll && showPinSymbol && showPinSymbol.showable)){
					this.figure.showPortSymbol();
				}
				
				if((showComponentName && showComponentName.showable && showComponentName.visiable)  
					|| (deviceShowAll && showComponentName && showComponentName.showable)){
					this.figure.showDeviceName();
				}
			}
		}
		
		return this.figure;
	},
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.refreshParameters<br>
	 * 函数功能：刷新参数显示<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	refreshParameters : function(){
		var paraString = '';
		var paraList   = this.findVisibleParameters();
		paraString     = this.formatParameters(paraList);
		if(this.figure.parameterFigure){
			this.figure.parameterFigure.setText(paraString);
		}
		return paraString;
	},
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.formatParameters<br>
	 * 函数功能：格式化需要显示的参数<br>
	 * 参数输入：paraList:draw2d.util.ArrayList(需要显示参数列表)<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	formatParameters : function(paraList){
		if(paraList.getSize() === 0){
			return "";
		}
		if(paraList.getSize() === 1){
			var para = paraList.get(0);
			return para.value.value + para.unit.unitType;
		}
		
		var str = '';
		paraList.each(function(i,para){
			str += (para.name + "=" + para.value.value + para.unit.unitType) + " ";
		});
		return str;
	},
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.findVisibleParameters<br>
	 * 函数功能：查找可以显示的参数列表<br>
	 * 函数返回：draw2d.util.ArrayList<br>
	 * 异常信息：无<br>
	 */
	findVisibleParameters : function(){
		if(!this.model){debugger;return;};
		if(!this.model.property.modelProperty){debugger;return;};
		if(!this.model.property.modelProperty.additional){debugger;return;};
		if(!this.model.property.modelProperty.additional.spiceProperties){debugger;return;};
		
		var parameters = this.model.property.modelProperty.additional.spiceProperties;
		var list = new draw2d.util.ArrayList();
		for(var i=0; i<parameters.length; i++){
			var para = parameters[i];
			if(para.showInfo){
				if(para.showInfo.showable && para.showInfo.visiable){
					list.add(para);
				}
			}
		}
		return list;
	},
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.handleModelEvent<br>
	 * 函数功能：处理模型事件<br>
	 * 参数输入：modelEvent:模型事件<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	handleModelEvent : function(modelEvent){
		
		var eventName = modelEvent.getEventName();
		var oldValue  = modelEvent.getOldValue();
		var newValue  = modelEvent.getNewValue();
		var figure    = this.getFigure();
		var modelPro  = this.getModel().property.modelProperty;

		switch(eventName){
			//DeviceModel事件定义：修改标签，label属性值改变
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_LABEL_CHANGED :{
				if(newValue.needCommandRequest){
					var handler = new Rainier.UI.V2.DeviceModelEventHandlerSetLabel();
					handler.setEditPart(this);
					handler.setOldLabel(oldValue.label);
					handler.setNewLabel(newValue.label);
					this.figure.getCanvas().getCommandStack().execute(handler);
				}else{
					figure.symbolLabelFigure.setText(newValue.label);					
				}
				return;
			}  	

			//DeviceModel事件定义：显示标签
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_SHOW_LABEL : {
				var showInfo = modelPro.showInfo;
				if(showInfo){
					if(showInfo.showLabel && showInfo.showLabel.showable){
						figure.showLabel();
						return;
					}
				}
				figure.unshowLabel();
				return;
			}

			//DeviceModel事件定义：隐藏标签
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_HIDE_LABEL : {
				var showInfo = modelPro.showInfo;
				if(showInfo){
					if(showInfo.showLabel && showInfo.showLabel.showable){
						figure.unshowLabel();
						return;
					}
				}
				figure.unshowLabel();
				return;
			}

			//DeviceModel事件定义：显示引脚的编号
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_SHOW_PIN_NUMBER : {
				var showInfo = modelPro.showInfo;
				if(showInfo){
					if(showInfo.showPinNumber && 
							showInfo.showPinNumber.showable && 
							showInfo.showPinNumber.visiable){
						figure.showPortNumber();
						return;
					}
				}
				figure.unshowPortNumber();
				return;
			}

			//DeviceModel事件定义：隐藏引脚的编号
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_HIDE_PIN_NUMBER : {
				figure.unshowPortNumber();
				return;
			}

			//DeviceModel事件定义：显示引脚的符号
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_SHOW_PIN_SYMBOL : {
				var showInfo = modelPro.showInfo;
				if(showInfo){
					if(showInfo.showPinSymbol && 
							showInfo.showPinSymbol.showable && 
							showInfo.showPinSymbol.visiable){
						figure.showPortSymbol();
						return;
					}
				}
				figure.unshowPortSymbol();
				return;
			}

			//DeviceModel事件定义：隐藏引脚的符号
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_HIDE_PIN_SYMBOL : {
				figure.unshowPortSymbol();
				return;
			}

			//DeviceModel事件定义：显示设备名称
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_SHOW_DEV_NAME : {
				var showInfo = modelPro.showInfo;
				if(showInfo){
					if(showInfo.showComponentName && 
							showInfo.showComponentName.showable && 
							showInfo.showComponentName.visiable){
						figure.showDeviceName();
						return;
					}
				}
				figure.unshowDeviceName();
				return;
			}

			//DeviceModel事件定义：隐藏设备名称
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_HIDE_DEV_NAME : {
				figure.unshowDeviceName();
				return;
			}

			//DeviceModel事件定义：修改模型参数
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_PARA_VALUE_CHANGED : {
				this.refreshParameters();
				return;
			}

			//DeviceModel事件定义：显示模型参数
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_SHOW_PARA  : {
				var str = this.refreshParameters();
				if(str){
					figure.showParameter();					
				}
				return;
			}

			//DeviceModel事件定义：隐藏模型参数
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_HIDE_PARA : {
				var str = this.refreshParameters();
				if(str){
					figure.showParameter();					
				}else{
					figure.unshowParameter();					
				}
				return;
			}

			//DeviceModel事件定义：显示所有模型参数
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_SHOW_ALL_PARA  : {
				figure.showParameter();	
				return;
			}

			//DeviceModel事件定义：隐藏所有模型参数
			case Rainier.UI.V2.DeviceModel.DEVICE_MODEL_EVENT_HIDE_ALL_PARA : {
				figure.unshowParameter();	
				return;
			}
			
			case Rainier.UI.V2.DynamicModel.DYNAMIC_MODEL_EVENT_CHANGE_STATE:{
				this.onDynamicChange(newValue);
				return;
			}
		};
		
		this._super(modelEvent);
	},
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.onDynamicChange<br>
	 * 函数功能：刷新动态元件(图片、文字等)<br>
	 * 参数输入：data：动态参数<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	onDynamicChange : function(data){
		var _this		 = this;
		var subImageList = this.figure.subImageList;
		var subTextList  = this.figure.subTextList;
		if (subImageList || subTextList) {
			var model		 = this.getModel();
			var property	 = model.getProperty();
			var uiProperty	 = property.uiProperty;
			var modelPro	 = property.modelProperty;

			var refreshSub	 = function(index,sub){				
				var condition 	= sub.condition;
				if(condition !== undefined){
					var spice 		= model.replaceSpiceModel(condition,modelPro);
					var regZero 	= new RegExp("(\\[V\\(0\\)\\])","g");
					spice 			= spice.replace(regZero,'0');
					spice	  		= _this.translateString('data',spice);
					//检测@@内容，数码管特例修改
					if (spice.indexOf('@') >= 0) {
						spice = _this.translateNixieTube(data,model,spice);
					}
					//TODO:动态元件显示规则
					try{
						//直流、交流的特殊处理 TODO:添加匹配规则  。。。淡淡的忧桑
						var ret 	= null;
						if(model instanceof Rainier.UI.V2.VirtualModel){
							var cviInfo = model.cviInfo;
							if(cviInfo ){
								ret = model.cviResult;//tranlateToDynamicText(data,spice);//产品要求同步，取消自定算法。。。。
							}
							else{
								ret = '';
							}
							_this.messageNum++;

						}
						else{
							ret 	= eval(spice);
							_this.messageNum = 100;
						}
						
						if (sub.image) {
							sub.visible = ret;
						}
						else{
							sub.text 	= ret;
						}
					}
					catch(e){
						console.log(e);
					}
				}
			}

			subImageList.each(refreshSub);
			subTextList.each(refreshSub);
			if(this.figure.updateDynamicSet){
				if(_this.messageNum >= 50){
					this.figure.updateDynamicSet();
					_this.messageNum = 0;
				}
			}
		}
		
	},

	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.translateString<br>
	 * 函数功能：替换[x]为(data[x] == undefined)?0:data[x]<br>
	 * 参数输入：spice ： 字符串<br>
	 * 参数输出：无<br>
	 * 函数返回：替换后字符串<br>
	 * 异常信息：无<br>
	 */
	translateString : function(data,spice){
		var reg		= new RegExp('\\[(.+?)\\]',"g");
		spice 		= spice.replace(reg,'(('+data+'[\'$1\'] == undefined)?0:'+data+'[\'$1\'])');
		return spice;
	},

	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.translateNixieTube<br>
	 * 函数功能：匹配数码管特殊规则<br>
	 * 参数输入：spice ： 字符串<br>
	 * 参数输出：无<br>
	 * 函数返回：替换后字符串<br>
	 * 异常信息：无<br>
	 */
	translateNixieTube : function(data,model,spice){
		var index = spice.indexOf('@');
		var spaceIndex 	= spice.indexOf('@',index+1);
		var replaceStr 	= spice.substr(index,spaceIndex-index+1);
		var reg 		= new RegExp("("+replaceStr+")","g");   

		var contentKey 	= spice.substr(index+1,spaceIndex-index-1);
		var count		= 0;
		var portList	= model.getHybridPorts().asArray();
		var length		= portList.length;
		$.each(portList,function(i,port){
			var node 	= port.getProperty().modelProperty.node;
			var value 	= 0;
			if (node > 0) {
				value 	= (data['V('+node+')'] > 2.5)?1:0;
			}
			count 		+= value*(Math.pow(2,length - i -1));
		})
		count			= count.toString(16);

		spice = '['+contentKey+'].indexOf(\''+count+'\') < 0';

		return spice;
	},
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.refreshFigure<br>
	 * 函数功能：完成figure的刷新功能<br>
	 * 参数输入：propertyKey ：修改参数的key值<br>
	 * 参数输入：propertyValue ：修改参数的value值<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	refreshFigure : function(propertyKey,propertyValue){
		if(propertyKey == "label"){
			var symbolLabelFigure = this.figure.symbolLabelFigure;
			symbolLabelFigure.setText(propertyValue);
		}
	},	
	
	/**
	 * 函数名称：Rainier.UI.V2.DeviceEditPart.addPortFigure<br>
	 * 函数功能：添加端口数字/符号引脚<br>
	 * 参数输入：i：index；port：端口<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	addPortFigure : function(i,port){
		var portProperty = port.property;
		var portLocator  = portProperty.modelProperty.locator;
		var symbolLocator = portProperty.modelProperty.symbolLocator;
		if(symbolLocator){
			this.figure.addPortSymbolLabelFigure({text:portProperty.modelProperty.symbol,
												symboltype:portProperty.modelProperty.symboltype,
												fontSize:8,
												fontColor:'#FF0000',
												angle:0},
												symbolLocator.type,
												symbolLocator.x-6,
												symbolLocator.y-9);
		}
		this.figure.addPortNumberLabelFigure({text:portProperty.modelProperty.id,fontSize:8,fontColor:'#FF00FF',angle:0},
				portLocator.type,portLocator.defaultX,portLocator.defaultY);
	},
	
});

